#! /usr/bin/env python
# -*- coding: utf-8 -*-

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from editor import CodeEditor, CodeEditorFactory
from time import time
from datetime import datetime

def now():
    return datetime.now().strftime('%x %X')

class MockEditor(QTextEdit):
    def __init__(self, *largs):
        QTextEdit.__init__(self, *largs)
        self.setAcceptDrops(True)
    
    def contextMenuEvent(self, e):
        print "Mock editor", e

class TabBarPane(QTabBar):
    
    def __init__(self, parent):
        QTabBar.__init__(self, parent)
        self.setAcceptDrops(True)
        self.m_dragStartPos = QPoint()
        
    def mousePressEvent(self, e):
        if e.button() & Qt.LeftButton:
            print "Drag start"
            self.m_dragStartPos = e.pos()
        QTabBar.mousePressEvent(self, e)
        
    def mouseMoveEvent(self, e):
        # If the left button isn't pressed anymore then return
        if not (e.buttons() & Qt.LeftButton):
            return
        
        print "OK"
        # If the distance is too small then return
        #manhattanLength = (e.pos() - self.m_dragStartPos).manhattanLength()
        #print manhattanLength, QApplication.startDragDistance()
        #if manhattanLength < QApplication.startDragDistance():
            #return
        
        #// initiate Drag
        drag = QDrag(self)
        # TODO: Cambiar este ícono
        drag.setPixmap(QPixmap(':/res/properties.png'))
        mimeData = QMimeData()
        #// a crude way to distinguish tab-reodering drags from other drags
        mimeData.setData("action", "tab-reordering")
        drag.setMimeData(mimeData)
        drag.exec_()
        

    def dragEnterEvent(self, e):
        mime = e.mimeData()
        formats = mime.formats()
        if formats.contains('action') and mime.data('action') == 'tab-reordering':
            e.acceptProposedAction()
        else:
            print mime
    
    def dropEvent(self, e):
        print "Drop event"
        fromIndex = self.tabAt(self.m_dragStartPos)
        toIndex = self.tabAt(e.pos())
        if fromIndex != toIndex:
            self.emit(SIGNAL('tabMoveRequested'), fromIndex, toIndex)
        e.acceptProposedAction()
    
    
    def keyPressEvent(self, e):
        print e
        QTabBar.keyPressEvent(self, e)

# =============================================================================
# TabPane
# =============================================================================
class TabPane(QTabWidget):
    UNTITLED_NAME_PATTERN = 'Untittled %d'
    DEFAULT_STYLE = '''
        QTabWidget::pane { / * The tab widget frame * /
             border-top: 2px solid #C2C7CB;
         }

         QTabWidget::tab-bar {
             left: 5px; / * move to the right by 5px * /
         }

         / * Style the tab using the tab sub-control. Note that
             it reads QTabBar _not_ QTabWidget * /
         QTabBar::tab {
             background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                         stop: 0 #E1E1E1, stop: 0.4 #DDDDDD,
                                         stop: 0.5 #D8D8D8, stop: 1.0 #D3D3D3);
             border: 2px solid #C4C4C3;
             border-bottom-color: #C2C7CB; / * same as the pane color * /
             border-top-left-radius: 4px;
             border-top-right-radius: 4px;
             min-width: 8ex;
             padding: 2px;
         }

         QTabBar::tab:selected, QTabBar::tab:hover {
             background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                         stop: 0 #fafafa, stop: 0.4 #f4f4f4,
                                         stop: 0.5 #e7e7e7, stop: 1.0 #fafafa);
         }
    '''
    '''
         /*
            
            QTabWidget {
            background-image: url(':/res/winicon.svg')
         
         
         }*/
    '''
    
    NO_EMPTY = False
    
    def __init__(self, parent = None):
        
        QTabWidget.__init__(self, parent)
        self.setStyleSheet(self.DEFAULT_STYLE)
        self.setup_ui()
        self.setup_actions()
        self.setup_menu()
        self._tabBar = TabBarPane(self)
        self.connect(self._tabBar, SIGNAL('tabMoveRequested'), self.moveTab)
        self.setTabBar(self._tabBar)
        #self.counter = 0
        self.factory = CodeEditorFactory(self)
        
        self.setAcceptDrops(True)
        QMetaObject.connectSlotsByName(self)
    
    def setup_ui(self):
        # Close button
        self.buttonClose = QPushButton(self)
        self.buttonClose.setFlat(True)
        self.buttonClose.setIcon(QIcon(':/res/close.png'))
        self.buttonClose.setToolTip('Colse')
        self.buttonClose.setObjectName('buttonClose')
        
        self.setCornerWidget(self.buttonClose, Qt.TopRightCorner)
        
        # Open button
        self.buttonNew = QPushButton(self)
        self.buttonNew.setFlat(True)
        self.buttonNew.setToolTip('New')
        self.buttonNew.setIcon(QIcon(':/res/document-new.png'))
        self.buttonNew.setObjectName('buttonNew')
        
        self.setCornerWidget(self.buttonNew, Qt.TopLeftCorner)
        
        # Load the background
        self.background = QPixmap(':/res/winicon.png')
        
    
    def setup_actions(self):
        self.actionNew = QAction('New document', self)
        self.connect(self.actionNew, SIGNAL('triggered()'), self.insert_new )
        
        
    
    def setup_menu(self):
        self.menu = QMenu()
        parent = self.parent()
        self.menu.addAction(parent.actionNewFile)
        self.menu.addAction(parent.actionOpenFile)
        self.menu.addSeparator()
        self.menu.addAction(parent.actionFilterThroughCommand)
        
        
    def moveTab (self, fromIndex, toIndex):
        '''
        Called when drag and drop occurs.
        '''
        widget = self.widget(fromIndex)
        icon = self.tabIcon(fromIndex)
        text = self.tabText(fromIndex)
        self.removeTab(fromIndex)
        self.insertTab(toIndex, widget, icon, text)
        self.setCurrentIndex(toIndex)
    
    #DnD handlers
    #void dragEnterEvent(QDragEnterEvent *event);
    #void dragMoveEvent(QDragMoveEvent *event);
    #void dragLeaveEvent(QDragLeaveEvent *event);
    #void dropEvent(QDropEvent *event);
    
    def dragEnterEvent(self, e):
        # TODO: Restrict contents?
        e.acceptProposedAction()
    
    def dropEvent(self, e):
        #print "Drop", e
        mime = e.mimeData()
        if mime.hasUrls():
            for url in mime.urls():
                self.factory.get_editor(url)
                print url, "dropped"
            
    
    
    def on_buttonClose_pressed(self):
        self.closeCurrent()
        #index = self.currentIndex()
        #if self.NO_EMPTY and self.count() == 1:
            #self.insert_new()
        #print "Remover"
        #self.removeTab( index )
        #curr = self.currentWidget()
        #if curr:
            #curr.setFocus(Qt.TabFocusReason)
        
    def closeCurrent(self):
        
        current = self.currentWidget()
        if current and current.requestClose():
            self.removeTab( self.currentIndex() )
            current = self.currentWidget()
            if current:
                current.setFocus(Qt.TabFocusReason)
        
    
    def on_buttonNew_pressed(self):
        self.insert_new()
        
    def insert_new(self, widget_or_path = None):
        '''
        Insert a new empty editor on the pane
        '''
        return self.factory.get_editor(None, return_widget = True)
        
    
    def add_document(self, doc):
        editor = CodeEditor(doc, self)
        self.addTab(editor)
    
    def contextMenuEvent( self, e ):
        self.menu.exec_( self.mapToGlobal( e.pos() ) )
        QTabWidget.contextMenuEvent(self, e)
    
    def mouseDoubleClickEvent( self, e):
        self.insert_new()
        #QTabWidget.mouseDoubleClickEvent(self, e)
    
    
    def _paintEvent(self, e):
        '''
        Draw the nice background :)
        '''
        QTabWidget.paintEvent(self, e)
        p = QPainter(self)
        rect, bg_rect = self.rect(), self.background.rect()
        if rect.width() > bg_rect.width() and rect.height() > bg_rect.height():
            pos_x = (rect.width() - bg_rect.width()) / 2
            pos_y = (rect.height() - bg_rect.height()) / 2
            p.drawPixmap(pos_x, pos_y, self.background)

# Resources
import resources_rc

def main():
    app = QApplication(sys.argv[1:])
    win = TabPane()
    win.setWindowTitle('Tab Pane test')
    for x in "Lorem ipsum dolor sit amet, consectetur adipiscing elit.".split():
        win.insert_new(x)
    win.setMinimumSize(600,300)
    win.show()
    sys.exit(app.exec_())
    
if __name__ == "__main__":
    main()
    